/*
 * @Author: sjr
 * @Date: 2021-01-24 13:52:55
 * @LastEditTime: 2021-01-24 23:23:16
 * @LastEditors: sjr
 * @Description: 描述
 * @FilePath: \leetcode\2.两数相加.js
 */
/*
 * @lc app=leetcode.cn id=2 lang=javascript
 *
 * [2] 两数相加
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
  var res = null
  var head = null
  var addNum = 0
  var cur = 0
  var curSum = 0
  var l1Val = 0
  var l2Val = 0
  while(l1 || l2){
    l1 ? l1Val = l1.val : l1Val = 0
    l2 ? l2Val = l2.val : l2Val = 0
    curSum = l1Val + l2Val + addNum
    addNum = curSum > 9 ? 1 : 0
    cur = curSum % 10
    if(!head){
      res = new ListNode(cur, null)
      head = res
    } else {
      res.next = new ListNode(cur, null)
      res = res.next
    }
 
    l1 && (l1 = l1.next)
    l2 && (l2 = l2.next)
  }

  if(!l1 && !l2) {
    if(addNum !== 0) {
      res.next = new ListNode(addNum, null)
    }
    return head
  }

};
// @lc code=end
